package io.github.source.config;

import android.text.TextUtils;

import com.github.catvod.utils.Json;

import io.github.source.bean.Config;
import io.github.source.bean.Live;
import io.github.source.config.impl.Callback;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: LiveConfig
 * @Description: TODO(直接播放)
 * @author: huangrongcai
 * @date: 2024/6/4
 * @Copyright: 黄嵘才（HuangRc)
 */
public class LiveConfig {

    private List<Live> lives;
    private Config config;
    private boolean sync;
    private Live home;

    private static class Loader {
        static volatile LiveConfig INSTANCE = new LiveConfig();
    }

    public static LiveConfig get() {
        return Loader.INSTANCE;
    }

    public LiveConfig clear() {
        getLives().clear();
        this.home = null;
        return this;
    }

    public LiveConfig config(Config config) {
        this.config = config;
        if (config.getUrl() == null) return this;
        this.sync = config.getUrl().equals(VodConfig.getUrl());
        return this;
    }

    public void parse(JsonObject object) {
        parseConfig(object, null);
    }

    private void parseConfig(JsonObject object, Callback callback) {
        /*解析直播*/
        List<JsonElement> lives = Json.safeListElement(object, "lives");

        for (JsonElement element : lives) {
            add(Live.objectFrom(element).check());
        }
        for (Live live : getLives()) {
            if (live.getName().equals(config.getHome())) setHome(live, true);
        }

        if (home == null) {
            setHome(getLives().isEmpty() ? new Live() : getLives().get(0), true);
        }
        if (callback != null) {
//            App.post(callback::success);Success
        }
    }

    private void add(Live live) {
        if (!getLives().contains(live)) getLives().add(live.sync());
    }

    public boolean needSync(String url) {
        return sync || (config == null) || TextUtils.isEmpty(config.getUrl()) || url.equals(config.getUrl());
    }

    public List<Live> getLives() {
        return lives == null ? lives = new ArrayList<>() : lives;
    }

    public Config getConfig() {
        return config == null ? Config.live() : config;
    }

    public Live getHome() {
        return home == null ? new Live() : home;
    }

    public void setHome(Live home) {
        setHome(home, false);
    }

    private void setHome(Live home, boolean check) {
        this.home = home;
        this.home.setActivated(true);
        config.home(home.getName()).update();
        for (Live item : getLives()) item.setActivated(home);

//        if (App.activity() != null && App.activity() instanceof LiveActivity) return;
//        if (check) if (home.isBoot() || Setting.isBootLive()) App.post(this::bootLive);
    }

}
